//
// Created by 麻再挺 on 2021/12/15.
//

#include "child_tree.h"


/**
 * 初始化
 * @param t 树
 */
Status CTree_Init(CTree *t) {
    int num = 10;
    int index[][3] = {{1, 2, 3},
                      {4, 5},
                      {},
                      {6},
                      {},
                      {},
                      {7, 8, 9},
                      {},
                      {},
                      {}};
    char chs[] = {'R', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'K'};
    // 赋值节点数量
    t->n = num;
    for (int i = 0; i < num; ++i) {
        // 赋值
        t->nodes[i].data = chs[i];
        // 申请第一个孩子内存空间
        t->nodes[i].firstChild = malloc(sizeof(ChildPtr));
        t->nodes[i].firstChild->next = NULL;
        ChildPtr *p = t->nodes[i].firstChild;
        // 遍历子孩子
        for (int j = 0; j < 3; ++j) {
            if (index[i][j] == 0) break;
            ChildPtr *tmp = malloc(sizeof(ChildPtr));
            // 设置指向为空
            tmp->next = NULL;
            tmp->child = index[i][j];
            // 指向下一个节点
            p->next = tmp;
            p = p->next;
        }
    }

    return OK;
}

/**
 * 查找元素
 * @param t 树
 * @param e 元素
 */
void CTree_Find_Kids(CTree *t, CTElemType e) {
    int hasKids = 0;
    // 遍历查找
    for (int i = 0; i < t->n; i++) {
        if (t->nodes[i].data == e) {
            ChildPtr *p = t->nodes[i].firstChild->next;
            while (p) {
                hasKids = 1;
                printf("查找到: %d, %c ", p->child, t->nodes[p->child].data);
                p = p->next;
            }
            break;
        }
    }
    if (hasKids == 0) {
        printf("此节点为叶子节点");
    }
}

/**
 * 打印
 * @param t 树
 */
void CTree_Print(CTree *t) {
    // 遍历
    for (int i = 0; i < t->n; ++i) {
        printf("data: %c", t->nodes[i].data);
        ChildPtr *p = t->nodes[i].firstChild->next;
        while (p) {
            printf(" -> %d, %c ", p->child, t->nodes[p->child].data);
            // 指向下一个
            p = p->next;
        }
        printf("\n");
    }
}